package com.ruoyi.web.controller.system;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWechatAuthService;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 小程序认证控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/auth")
public class MiniappAuthController extends BaseController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWechatAuthService wechatAuthService;

    /**
     * 小程序登录
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @Anonymous
    @PostMapping("/miniapp/login")
    public AjaxResult miniappLogin(@RequestBody LoginBody loginBody)
    {
        try
        {
            // 验证用户名密码
            if (!"admin".equals(loginBody.getUsername()) || !"admin123".equals(loginBody.getPassword()))
            {
                return AjaxResult.error("用户名或密码错误");
            }

            // 直接进行用户认证，跳过验证码验证
            String token = loginService.loginWithoutCaptcha(loginBody.getUsername(), loginBody.getPassword());
            
            // 直接通过用户名查询用户信息
            SysUser user = userService.selectUserByUserName(loginBody.getUsername());
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("expiresIn", 7200); // 2小时过期
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getUserId());
            userInfo.put("userName", user.getUserName());
            userInfo.put("nickName", user.getNickName());
            userInfo.put("avatar", user.getAvatar());
            data.put("userInfo", userInfo);

            return AjaxResult.success("登录成功", data);
        }
        catch (Exception e)
        {
            logger.error("小程序登录失败", e);
            return AjaxResult.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 刷新Token
     * 
     * @param requestBody 刷新Token请求
     * @return 结果
     */
    @PostMapping("/refresh")
    public AjaxResult refreshToken(@RequestBody Map<String, String> requestBody)
    {
        try
        {
            String refreshToken = requestBody.get("refreshToken");
            if (refreshToken == null || refreshToken.isEmpty())
            {
                return AjaxResult.error("刷新Token不能为空");
            }

            // 这里可以实现刷新Token的逻辑
            // 目前简单返回错误，提示重新登录
            return AjaxResult.error("请重新登录");
        }
        catch (Exception e)
        {
            logger.error("刷新Token失败", e);
            return AjaxResult.error("刷新Token失败：" + e.getMessage());
        }
    }

    /**
     * 微信授权登录
     * 
     * @param requestBody 微信授权信息
     * @return 结果
     */
    @Anonymous
    @PostMapping("/wechat/login")
    public AjaxResult wechatLogin(@RequestBody Map<String, String> requestBody)
    {
        try
        {
            String code = requestBody.get("code");
            if (code == null || code.isEmpty())
            {
                return AjaxResult.error("微信授权码不能为空");
            }

            // 调用微信授权服务
            Map<String, Object> loginResult = wechatAuthService.wechatLogin(code);
            
            if (!(Boolean) loginResult.get("success"))
            {
                return AjaxResult.error("微信登录失败：" + loginResult.get("error"));
            }

            SysUser user = (SysUser) loginResult.get("user");
            String openid = (String) loginResult.get("openid");
            Boolean isNewUser = (Boolean) loginResult.get("isNewUser");

            // 添加日志：记录从数据库查询到的用户信息
            logger.info("登录查询到的用户信息 - userId: {}, userName: {}, wechatNickname: {}, wechatAvatar: {}", 
                    user.getUserId(), user.getUserName(), user.getWechatNickname(), user.getWechatAvatar());

            // 为微信用户生成JWT token（不需要密码验证）
            // 为微信用户设置基本权限
            Set<String> permissions = new HashSet<>();
            
            // 反馈相关权限
            permissions.add("system:feedback:list");
            permissions.add("system:feedback:add");
            permissions.add("system:feedback:query");
            
            // 重点工作相关权限
            permissions.add("system:work:list");
            permissions.add("system:work:query");
            permissions.add("system:work:add");
            permissions.add("system:work:edit");
            
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissions);
            String token = tokenService.createToken(loginUser);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("expiresIn", 7200); // 2小时过期
            data.put("isNewUser", isNewUser);
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getUserId());
            userInfo.put("userName", user.getUserName());
            // 优先返回微信昵称与头像；若不存在则回退到系统昵称与头像
            String displayNick = com.ruoyi.common.utils.StringUtils.isNotEmpty(user.getWechatNickname()) ?
                    user.getWechatNickname() : (com.ruoyi.common.utils.StringUtils.isNotEmpty(user.getNickName()) ? user.getNickName() : "微信用户");
            String displayAvatar = com.ruoyi.common.utils.StringUtils.isNotEmpty(user.getWechatAvatar()) ?
                    user.getWechatAvatar() : user.getAvatar();
            userInfo.put("nickName", displayNick);
            userInfo.put("avatar", displayAvatar);
            userInfo.put("wechatOpenid", user.getWechatOpenid());
            
            // 直接返回数据库中的值，即使为null也要返回（前端需要知道是否为null）
            userInfo.put("wechatNickname", user.getWechatNickname());
            userInfo.put("wechatAvatar", user.getWechatAvatar());
            
            userInfo.put("userType", user.getUserType());
            data.put("userInfo", userInfo);
            
            // 添加日志：记录返回给前端的用户信息
            logger.info("返回给前端的用户信息 - wechatNickname: {}, wechatAvatar: {}", 
                    userInfo.get("wechatNickname"), userInfo.get("wechatAvatar"));

            String message = isNewUser ? "注册并登录成功" : "登录成功";
            return AjaxResult.success(message, data);
        }
        catch (Exception e)
        {
            logger.error("微信登录失败", e);
            return AjaxResult.error("微信登录失败：" + e.getMessage());
        }
    }

    /**
     * 更新微信用户信息
     * 
     * @param requestBody 用户信息
     * @return 结果
     */
    @PostMapping("/wechat/updateUserInfo")
    public AjaxResult updateWechatUserInfo(@RequestBody Map<String, Object> requestBody)
    {
        try
        {
            // 获取当前登录用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser == null)
            {
                return AjaxResult.error("用户未登录");
            }

            Long userId = loginUser.getUserId();
            SysUser user = userService.selectUserById(userId);
            
            if (user == null)
            {
                return AjaxResult.error("用户不存在");
            }

            // 更新微信用户信息
            if (requestBody.containsKey("nickName"))
            {
                user.setNickName((String) requestBody.get("nickName"));
            }
            if (requestBody.containsKey("wechatNickname"))
            {
                user.setWechatNickname((String) requestBody.get("wechatNickname"));
            }
            if (requestBody.containsKey("wechatAvatar"))
            {
                user.setWechatAvatar((String) requestBody.get("wechatAvatar"));
            }
            if (requestBody.containsKey("wechatGender"))
            {
                user.setWechatGender((String) requestBody.get("wechatGender"));
            }
            if (requestBody.containsKey("wechatCity"))
            {
                user.setWechatCity((String) requestBody.get("wechatCity"));
            }
            if (requestBody.containsKey("wechatProvince"))
            {
                user.setWechatProvince((String) requestBody.get("wechatProvince"));
            }
            if (requestBody.containsKey("wechatCountry"))
            {
                user.setWechatCountry((String) requestBody.get("wechatCountry"));
            }

            int result = userService.updateUser(user);
            if (result > 0)
            {
                return AjaxResult.success("更新用户信息成功");
            }
            else
            {
                return AjaxResult.error("更新用户信息失败");
            }
        }
        catch (Exception e)
        {
            logger.error("更新微信用户信息失败", e);
            return AjaxResult.error("更新用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 退出登录
     * 
     * @return 结果
     */
    @PostMapping("/logout")
    public AjaxResult logout()
    {
        try
        {
            // 获取当前登录用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null)
            {
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
            }
            return AjaxResult.success("退出成功");
        }
        catch (Exception e)
        {
            logger.error("退出登录失败", e);
            return AjaxResult.error("退出失败：" + e.getMessage());
        }
    }
}
